import React from "react"
import styles from '@/assets/css/confirm.module.css'

export default () => {
    const [roomid] = useState(React.params('roomid') ?? 0)

    let [roomInfo, SetRoomInfo] = useState({flag_text: [], price: 0, name: '', thumb_text: ''})
    let [dateShow, SetDateShow] = useState(false)
    let [guestList, SetGuestList] = useState([])
    let [guestShow, SetGuestShow] = useState(false)
    let [couponList, SetCouponList] = useState<any[]>([])
    let [couponShow, SetCouponShow] = useState(false)
    let [payShow, SetPayShow] = useState(false)

    // 选择天数以及使用优惠后的价格
    let [totalPrice, SetTotalPrice] = useState(0)

    // 原价
    let [originPrice, SetOriginPrice] = useState(0)

    // 入住天数
    let [day, SetDay] = useState(0)

    //支付信息
    const [payList] = React.useState([[
        { label: '余额支付', value: 'money' },
        { label: '微信支付', value: 'wx' },
        { label: '支付宝支付', value: 'zfb' },
    ]])

    // 订单信息数据
    const [orderInfo, SetOrderInfo] = React.useState({
        remark: '',
        //价格信息
        origin_price: 0,
        price: 0,
        //优惠券
        couponid: '',
        couponstr: '暂无优惠券信息',
        //日期
        datestr: '',
        starttime: 0,
        endtime: 0,
        //住客
        guest: '',
        gueststr: '请选择住客信息',
        guestids: [],
        //支付方式
        paystr: '余额支付',
        pay: 'money'
    })

    useEffect(() => {
        GetRoomInfo()
        GetCurrentDate()
        GetGuestList()
        GetCouponList()
    }, [roomid])

    // 当订单信息有变化时 重新计算总价
    useEffect(() => {
        Total()
    }, [orderInfo, roomInfo])

    // 计算订单总价
    const Total = () => {        
        let startTime = orderInfo.starttime
        let endTime = orderInfo.endtime

        // 时间差
        let duration = endTime - startTime
        let day = Math.floor(duration / 86400)

        // 计算结果保留两位小数
        let truncateToTwoDecimals = (num: number): any => Math.trunc(num * 100) / 100

        // 计算选择入住时间后的总价
        let dayPrice = truncateToTwoDecimals(day * roomInfo.price)
        let disPrice = dayPrice

        // 选择优惠劵
        if(orderInfo.couponid && couponList[0])
        {
            // 获取选中的优惠劵的信息
            // if(couponList.length > 0)
            // {

            // }
            let list: any = couponList[0]

            let coupon = list.find((item: any) => item.value = orderInfo.couponid)
            
            // 计算折扣后的价格
            if(coupon) disPrice = truncateToTwoDecimals(disPrice * coupon.rate)
        }

        // 修改价格与天数
        SetOriginPrice(dayPrice)
        SetTotalPrice(disPrice)
        SetDay(day)
    }

    // 获取房型信息
    const GetRoomInfo = async () => {
        let result = await React.request.post('/room/RoomInfo', {roomid})

        if(result.code == 0)
        {
            React.toast(result.msg, 'fail', 'back')
            return false
        }

        SetRoomInfo(result.data.info)
    }
    
    // 日期组件默认日期
    const DefaultDateRange: [Date, Date] = [
        new Date(),
        new Date(new Date().getTime() + 86400000)
    ]

    // 获取当前时间 初始化默认时间
    const GetCurrentDate = () => {        
        let datestr = `${new Date(DefaultDateRange[0]).toLocaleDateString()} - ${new Date(DefaultDateRange[1]).toLocaleDateString()}`
        
        // 标准时间转换为时间戳
        let starttime = Date.parse(new Date(DefaultDateRange[0]).toLocaleDateString()) / 1000
        let endtime = Date.parse(new Date(DefaultDateRange[1]).toLocaleDateString()) / 1000

        SetOrderInfo({
            ...orderInfo,
            starttime,
            endtime,
            datestr
        })
    }

    // 确认选择日期
    const DateChange = (value: any) => {
        let datestr = `${new Date(value[0]).toLocaleDateString()} - ${new Date(value[1]).toLocaleDateString()}`
        
        // 标准时间转换为时间戳
        let starttime = Date.parse(new Date(value[0]).toLocaleDateString()) / 1000
        let endtime = Date.parse(new Date(value[1]).toLocaleDateString()) / 1000

        SetOrderInfo({
            ...orderInfo,
            starttime,
            endtime,
            datestr
        })
    }

    // 获取住客信息
    const GetGuestList = async () => {
        let result = await React.request.post('/room/GuestList', {busid: React.business.id})
    
        if(result && result.code == 1) SetGuestList(result.data)
    }

    // 确认住客信息
    const GuestChange = (value: string[]) => {
        let gueststr: any = []
        let guestids: any = []

        guestList.map((item: any) => {
            if(value.includes(item.id))
            {
                gueststr.push(item.nickname)
                guestids.push(item.id)
            }
        })

        let names = gueststr.join('、')
        let ids = guestids.join(',')

        SetOrderInfo({
            ...orderInfo,
            gueststr: names,
            guest: ids,
            guestids
        })
    }

    // 获取优惠劵信息
    const GetCouponList = async () => {
        let result = await React.request.post('/room/CouponList', {busid: React.business.id})

        if(result && result.code == 1){
            let list: any = result.data
            let data: any = []

            list.map((item: any) => {
                data.push({
                    label: `${item.coupon.title} - ${(item.coupon.rate * 10).toFixed(1)}折`,
                    value: item.id,
                    rate: item.coupon.rate
                })
            })

            // 二维数组结构
            SetCouponList([data])
        }
    }

    // 确认选择优惠劵
    const CouponChange = (value: any) => {
        SetCouponShow(false)

        let couponstr = ''

        if(couponList.length <= 0)
        {
            React.toast('暂无可使用优惠劵', 'fail')
            return false
        }

        // 获取第一个选项
        let list: any = couponList[0]

        list.map((item: any) => {
            if(item.value == value[0])
            {
                couponstr = item.label
            }
        })

        SetOrderInfo({
            ...orderInfo,
            couponstr,
            couponid: value[0]
        })
    }

    // 确认支付方式
    const PayChange = (value: any) => {
        SetPayShow(false)

        let paystr = ''

        let list: any = payList[0]

        list.map((item: any) => {
            if(item.value == value[0]) paystr = item.label
        })

        SetOrderInfo({
            ...orderInfo,
            paystr,
            pay: value[0]
        })
    }

    // 订单备注
    const RemarkChange = (e: any) => {
        SetOrderInfo({
            ...orderInfo,
            remark: e
        })
    }

    // 订单价格显示
    const OrderPrice = () => {
        if(totalPrice == originPrice)
        {
            return (
                <div className={styles.text}>
                    <span>总价:</span>
                    <span>￥{totalPrice}</span>
                </div>
            )
        }else
        {
            return (
                <div className={styles.text}>
                    <span>优惠价格:</span>
                    <span>￥{totalPrice}</span>
                    <s>原价：￥{originPrice}</s>
                </div>
            )
        }
    }

    // 提交预订订单
    const ConfirmOrder = async () => {
        // 判断是否登录
        if(Object.getOwnPropertyNames(React.business).length <= 0)
        {
            React.toast('请先登录', 'fail')
            return false
        }

        // 如果没有选择日期
        if(day <= 0) return React.toast('请选择入住日期', 'fail')

        // 如果没有选择住客信息
        if(orderInfo.guestids.length <= 0) return React.toast('请选择住客信息', 'fail')

        // 组装数据
        let data = {
            busid: React.business.id,
            roomid: roomid,
            guest: orderInfo.guest,
            starttime: orderInfo.starttime,
            endtime: orderInfo.endtime,
            couponid: orderInfo.couponid ?? '',
            remark: orderInfo.remark,
            pay: orderInfo.pay
        }

        // 余额支付
        if(orderInfo.pay == 'money')
        {
            let result = await React.request.post('/room/OrderAdd', data)

            if(result.code == 0)
            {
                React.toast(result.msg, 'fail')
                return false
            }

            React.toast(result.msg, 'success', result.url)
            return false
        } else
        {
            // 其他类型支付
            let result = await React.request.post('/room/OrderAdd', data)

            if(result.code == 0)
            {
                React.toast(result.msg, 'fail')
                return false
            }

            // 跳转到收银台界面
            React.toast(result.msg, 'success', `/room/pay?payid=${result.data.id}`)
            return false
        }
    }

    return (
        <>
            <div className={styles.header}>
                <React.UI.NavBar back="返回" onBack={() => React.navigate(-1)}>填写预订信息</React.UI.NavBar>
            </div>

            <div className={styles.skeleton}>
                {/* 房间信息 */}
                <div className={styles.detail}>
                    <div className={styles.thumb}>
                        <img src={roomInfo.thumb_text} alt="" />
                    </div>
                    <div className={styles.right}>
                        <p>{roomInfo.name}</p>
                        <p>￥{roomInfo.price} / 晚</p>
                        <div className={styles.tips}>
                            {roomInfo.flag_text && roomInfo.flag_text.map((flag: any, index: any) => (
                                <React.UI.Tag 
                                    color='primary'
                                    fill='outline'
                                    style={{'--border-radius': '6px'}}
                                    key={index}
                                >
                                    {flag}
                                </React.UI.Tag>
                            ))}
                        </div>
                    </div>
                </div>

                {/* 入住信息 */}
                <div className={styles.skeleton_rect}>
                    {/* 入住时间 */}
                    <div className={styles.item} onClick={() => SetDateShow(true)}>
                        <label>入住日期</label>
                        <React.UI.Input 
                            type="text"
                            className={styles.item_right}
                            placeholder="请选择入住日期"
                            value={orderInfo.datestr}
                            readOnly
                        />
                        <React.ICON.RightOutline fontSize={16} />
                    </div>

                    {/* 日期选择器 */}
                    <React.UI.CalendarPicker
                        visible={dateShow}
                        min={new Date()}
                        defaultValue={DefaultDateRange}
                        selectionMode='range'
                        onClose={() => SetDateShow(false)}
                        onMaskClick={() => SetDateShow(false)}
                        onConfirm={DateChange}
                    >
                    </React.UI.CalendarPicker>

                    {/* 住客信息 */}
                    <div className={styles.item}>
                        <label>住客信息</label>
                        <div className={orderInfo.guestids.length > 0 ? styles.item_right : styles.item_rights} onClick={() => SetGuestShow(true)}>{orderInfo.gueststr}</div>
                        <React.ICON.RightOutline fontSize={12} />
                    </div>

                    {/* 住客选择器 */}
                    <React.UI.Popup
                        visible={guestShow}
                        destroyOnClose
                        onMaskClick={() => SetGuestShow(false)}
                        bodyStyle={{
                            borderTopLeftRadius: '8px',
                            borderTopRightRadius: '8px',
                            padding: '10px'
                        }}
                    >
                         <div
                            style={{ height: '50vh', overflowY: 'scroll', padding: '20px' }}
                            >
                            <React.UI.CheckList
                                multiple
                                defaultValue={orderInfo.guestids}
                                onChange={GuestChange}
                            >
                                {guestList && guestList.map((item:any, key:number) => (
                                    <React.UI.CheckList.Item key={key} value={item.id}>
                                        {item.nickname}（{item.mobile}）
                                    </React.UI.CheckList.Item>
                                ))}
                            </React.UI.CheckList>

                        </div>
                        <React.UI.Button style={{marginBottom: '10px'}} color='primary' block fill='outline' onClick={() => SetGuestShow(false)}>确认</React.UI.Button>
                    </React.UI.Popup>
                </div>

                {/* 优惠券 */}
                <div className={styles.skeleton_price}>
                    <div className={styles.tips}>优惠券</div>
                    <p>{orderInfo.couponstr}</p>
                    <React.UI.Button size="mini" color="primary" onClick={() => SetCouponShow(true)}>选择</React.UI.Button>

                    {/* 弹框选项 */}
                    <React.UI.Picker
                        visible={couponShow}
                        columns={couponList}
                        onClose={() => SetCouponShow(false)}
                        onConfirm={CouponChange}
                    >
                    </React.UI.Picker>
                </div>

                {/* 支付方式 */}
                <div className={styles.skeleton_price}>
                    <div className={styles.tips}>支付方式</div>
                    <p>{orderInfo.paystr}</p>
                    <React.UI.Button size="mini" color="primary" onClick={() => SetPayShow(true)}>选择</React.UI.Button>

                    <React.UI.Picker
                        columns={payList}
                        visible={payShow}
                        onClose={() => SetPayShow(false)}
                        onConfirm={PayChange}
                    >
                    </React.UI.Picker>
                </div>

                {/* 订单备注 */}
                <div className={styles.skeleton_price}>
                    <div className={styles.tips} style={{width: '80px'}}>订单备注</div>
                    <React.UI.Input className={styles.remark} placeholder={'请输入订单备注'} value={orderInfo.remark} onChange={RemarkChange} />
                </div>

                {/* 费用 */}
                <div className={styles.skeleton_price}>
                    <div className={styles.tips}>房间费用</div>
                    <div className={styles.prices}>
                        <span>￥{originPrice}</span>
                        <span>共 {day} 晚</span>
                    </div>
                </div>
            </div>

            <div className={styles.comfirm_foot_bar}>
                <OrderPrice />
                <React.UI.Button color='primary' shape='rounded' onClick={ConfirmOrder}>提交订单</React.UI.Button>
            </div>
        </>
    )
}